package com.audaque.encoding.coding;

import com.audaque.encoding.entity.CronDO;
import com.audaque.encoding.mapper.CronMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class CodingTask {

    private final ScheduledTaskRegistrar taskRegistrar = new ScheduledTaskRegistrar();

    @Resource
    private CronMapper cronMapper;

    @Resource
    private CodingV3Service codingV3Service;

    private ThreadPoolTaskScheduler taskScheduler;

    @PostConstruct
    public void init() {
        log.info("初始化定时任务");

        // 初始化调度器，只创建一次
        if (taskScheduler == null) {
            taskScheduler = new ThreadPoolTaskScheduler();
            taskScheduler.setPoolSize(5);
            taskScheduler.setThreadNamePrefix("coding-task-");
            taskScheduler.initialize(); // 初始化调度器
        }

        // 关联调度器
        taskRegistrar.setTaskScheduler(taskScheduler);

        // 从数据库加载定时任务
        List<CronDO> cronList = cronMapper.selectList(Wrappers.emptyWrapper());

        // 添加定时任务
        if (cronList != null && !cronList.isEmpty()) {
            for (CronDO cron : cronList) {
                try {
                    String cronExpression = cron.getCron();
                    taskRegistrar.addCronTask(() -> run(cron.getType()), cronExpression);
                } catch (Exception e) {
                    log.error("添加定时任务失败", e);
                }
            }
        }

        // 开始调度
        taskRegistrar.afterPropertiesSet();
        log.info("定时任务初始化完成");
    }

    public void startInit() {
        log.info("重新初始化定时任务");

        // 取消当前所有任务并重新初始化
        taskRegistrar.destroy();
        log.info("取消已经存在的任务");

        // 重新调用 init() 方法
        init();
    }

    public void run(Integer type) {
        codingV3Service.startTask(type);
    }

    // 添加一个方法关闭调度器
    public void shutdownScheduler() {
        if (taskScheduler != null) {
            taskScheduler.shutdown();
        }
    }
}
